import multiprocessing
import sys
import time as systime
from time import sleep
from datetime import datetime, time
from logging import INFO

from vnpy.event import EventEngine
from vnpy.trader.setting import SETTINGS
from vnpy.trader.engine import MainEngine

from vnpy_ctp import CtpGateway
# 1
# from vnpy_uft import UftGateway
# from vnpy_tts import TtsGateway
from vnpy_ctastrategy import CtaStrategyApp
from vnpy_ctastrategy.base import EVENT_CTA_LOG


SETTINGS["log.active"] = True
SETTINGS["log.level"] = INFO
SETTINGS["log.console"] = True


ctp_setting = {
    "用户名": "103929",
    "密码": "12Qs23!sn2",
    "经纪商代码": "9999",
    # 2
    # "交易服务器": "218.202.237.33:10203",
    # "行情服务器": "218.202.237.33:10213",
    # "交易服务器": "180.168.146.187:10130",
    # "行情服务器": "180.168.146.187:10131",
    "交易服务器": "180.168.146.187:10201",
    "行情服务器": "180.168.146.187:10211",
    "产品名称": "simnow_client_test",
    "授权编码": "0000000000000000",
    "产品信息": "Max产品信息"
}

uft_setting = {
    "用户名": "941001133",
    "密码": "111111",
    "经纪商代码": "9999",
    "交易服务器": "101.71.132.51:9006",
    "行情服务器": "101.71.132.51:9106",
    "服务器类型": "期货",
    "产品名称": "Hs_JT_1.0",
    "授权编码": "20191127JTV1",
    "委托类型": "7"
}

tts_setting = {
    "用户名": "5373",
    "密码": "123456",
    "经纪商代码": "1",
    "交易服务器": "tcp://121.37.80.177:20002",
    "行情服务器": "tcp://121.37.80.177:20004",
    "产品名称": "1",
    "授权编码": "1",
    "产品信息": "1"
}

# CTA策略信息
# 3
# class_name = "DbTest"
class_name = "TrackTest"
strategy_name = "track0103-2"
vt_symbol = "c2303.DCE"

strategy_setting = {
    # "fast_window": 5,
    # "slow_window": 10
}

def run_child():
    """
    Running in the child process.
    """
    SETTINGS["log.file"] = True

    event_engine = EventEngine()
    main_engine = MainEngine(event_engine)
    
    # 4
    main_engine.add_gateway(CtpGateway)
    # main_engine.add_gateway(UftGateway)
    # main_engine.add_gateway(TtsGateway)
    cta_engine = main_engine.add_app(CtaStrategyApp)
    main_engine.write_log("主引擎创建成功")

    log_engine = main_engine.get_engine("log")
    event_engine.register(EVENT_CTA_LOG, log_engine.process_log_event)
    main_engine.write_log("注册日志事件监听")

    # 5
    main_engine.connect(ctp_setting, "CTP")
    # main_engine.connect(uft_setting, "UFT")
    # main_engine.connect(tts_setting, "TTS")
    main_engine.write_log("连接CTP接口")

    sleep(5)

    cta_engine.init_engine()

    # 创建属于我们自己的策略，首次创建成功后会将参数写入到C:\Users\Administrator\.vntrader文件夹下的cta_strategy_setting.json文件内
    if strategy_name not in cta_engine.strategies:
        main_engine.write_log(f"创建{strategy_name}策略")
        cta_engine.add_strategy(class_name, strategy_name, vt_symbol, strategy_setting)
    else:
        cta_engine.update_strategy_setting(strategy_name, strategy_setting)

    # 初始化刚创建的策略
    cta_engine.init_strategy(strategy_name)

    main_engine.write_log("CTA策略初始化完成")

    # 留有足够的时间来进行策略初始化
    sleep(2)

    # 启动刚创建的策略
    cta_engine.start_strategy(strategy_name)
    main_engine.write_log("CTA策略已经启动")
    # cta_engine.init_all_strategies()
    # sleep(60)   # Leave enough time to complete strategy initialization
    # main_engine.write_log("CTA策略全部初始化")

    # cta_engine.start_all_strategies()
    # main_engine.write_log("CTA策略全部启动")

    while True:
        sleep(1)


def run_parent():
    """
    Running in the parent process.
    """
    print("启动CTA策略守护父进程")

    child_process = None

    while True:
        trading = True

        # Start child process in trading period
        if trading and child_process is None:
            print("启动子进程")
            child_process = multiprocessing.Process(target=run_child)
            child_process.start()
            print("子进程启动成功")

        # 非记录时间则退出子进程
        if not trading and child_process is not None:
            if not child_process.is_alive():
                child_process = None
                print("子进程关闭成功")

        sleep(5)


if __name__ == "__main__":
    run_parent()
